package com.weilele.mvvm.utils.glide;

import androidx.annotation.WorkerThread;

import com.weilele.mvvm.utils.net.OkHttpCertUtils;

import java.util.HashMap;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public final class OkHttpLoadImage {
    //一定要记得unRegister,这里存放的是key以及OnProgressListener
    //实际上,我们最好采用软引用,这样更加的安全,毕竟我们无法感知View的生命周期
    private static final HashMap<String, OnProgressListener> progressListenerMap;
    //添加了拦截的OkHttpClient
    private OkHttpClient okHttpClient;

    static {
        progressListenerMap = new HashMap<>();
    }

    private OkHttpLoadImage() {
        initOkHttp();
    }

    /**
     * 构建一个OkHttp的实例
     * ProgressResponseBody 是一个比较关键的类,他提供了进度
     */
    private void initOkHttp() {
        okHttpClient = OkHttpCertUtils.createCertOkHttpBuilder()
                .addNetworkInterceptor(chain -> {
                    Request request = chain.request();
                    Response response = chain.proceed(request);
                    OkHttpProgressResponseBody body = new OkHttpProgressResponseBody(response, request.url().toString());
                    //添加监听,使得当前类知道进度
                    body.addOnResponseListener(responseListener);
                    return response.newBuilder()
                            .body(body)
                            .build();
                })
                .build();
    }

    private static class SingletonHolder {
        private static final OkHttpLoadImage instance = new OkHttpLoadImage();
    }

    public static OkHttpClient INSTANCE() {
        return SingletonHolder.instance.okHttpClient;
    }

    private static final OkHttpProgressResponseBody.OnResponseListener responseListener = new OkHttpProgressResponseBody.OnResponseListener() {
        @Override
        public void update(String key, float progress) {
            //去寻找这个key，并传回去当前的进度
            OnProgressListener listener = progressListenerMap.get(key);
            if (listener != null) {
                listener.onProgress(progress);
            }
        }
    };

    /**
     * 注册进度的回调
     */
    public static void register(OnProgressListener listener) {
        //可能会有多个View注册，但是我们只回调当前这个
        if (listener != null) {
            progressListenerMap.put(listener.getKey(), listener);
        }
    }

    /**
     * 取消监听
     *
     * @param listener view
     */
    public static void unRegister(OnProgressListener listener) {
        if (listener != null) {
            progressListenerMap.remove(listener.getKey());
        }
    }

    /**
     * 监听进度的接口
     * 如果是从缓存加载，这里回调就不会走
     */
    public interface OnProgressListener {
        //回调当前的进度给View
        @WorkerThread
        void onProgress(float progress);

        //获取当前View资源的key(URL即可)
        String getKey();
    }
}